<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryForm" :inline="true">
        <!-- StartDate  EndDate -->
        <el-form-item prop="keywords">
          <el-input v-model="queryForm.keywords" placeholder="请输入关键字" clearable style="width: 200px" />
          <el-button type="primary" style="margin-left: 0; border-radius: 0" @click="handleQuery"> 搜索 </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-container">
      <el-row :gutter="20">
        <el-col :span="24" :offset="0">
          <el-button v-if="permissions.create" type="primary" size="default" @click="Create">新增</el-button>
        </el-col>
        <el-col :span="24" :offset="0" style="margin-top: 10px">
          <el-table
            ref="tableRef"
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            :show-overflow-tooltip="{ effect: 'light' }"
            @select="handleCurrentChange"
          >
            <el-table-column type="selection" align="center" width="50" />
            <el-table-column label="项目名称" prop="name" min-width="250" />
            <el-table-column label="项目编号" prop="prjNum" min-width="200" />
            <el-table-column label="项目种类" prop="fundsSourceName" min-width="120" />
            <el-table-column label="行业主管部门" prop="industryTypeName" min-width="120" />
            <el-table-column label="工程进度" prop="prjStatusName" min-width="80">
              <template #default="scope">
                <span v-if="scope.row.prjStatus == 1">
                  <el-text type="info"> {{ scope.row.prjStatusName }} </el-text>
                </span>
                <span v-if="scope.row.prjStatus == 2">
                  <el-text> {{ scope.row.prjStatusName }} </el-text>
                </span>
                <span v-if="scope.row.prjStatus == 3">
                  <el-text type="primary"> {{ scope.row.prjStatusName }} </el-text>
                </span>
                <span v-if="scope.row.prjStatus == 4">
                  <el-text type="warning"> {{ scope.row.prjStatusName }} </el-text>
                </span>
                <span v-if="scope.row.prjStatus == 5">
                  <el-text type="danger"> {{ scope.row.prjStatusName }} </el-text>
                </span>
                <span v-if="scope.row.prjStatus == 6">
                  <el-text type="success"> {{ scope.row.prjStatusName }} </el-text>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="项目类型" prop="categoryName" min-width="100" />
            <el-table-column label="建设性质" prop="propertyNumName" min-width="80" />
            <!-- <el-table-column label="建设规模" prop="sizeTypeName" min-width="80" /> -->
            <el-table-column label="所在城市" prop="cityCode" min-width="80">
              <template #default="scope">
                <span v-if="scope.row.cityCode">
                  {{ fomartCityName(scope.row.cityCode) }}
                </span>
                <span v-else> 未知 </span>
              </template>
            </el-table-column>
            <el-table-column label="审核状态" prop="auditStatusName" min-width="80">
              <template #default="scope">
                <span v-if="scope.row.auditStatus == 0">
                  <el-text type="warning"> {{ scope.row.auditStatusName }} </el-text>
                </span>
                <span v-if="scope.row.auditStatus == 1">
                  <el-text type="success"> {{ scope.row.auditStatusName }} </el-text>
                </span>
                <span v-if="scope.row.auditStatus == -1">
                  <el-text type="danger"> {{ scope.row.auditStatusName }} </el-text>
                </span>
              </template>
            </el-table-column>
            <el-table-column label="实际开工时间" prop="startDate" min-width="120" />
            <el-table-column label="操作" fixed="right" max-width="260" min-width="160">
              <template #default="scope">
                <el-button
                  v-if="permissions.update && scope.row.auditStatus == 0"
                  link
                  size="small"
                  type="primary"
                  @click="Edit(scope.row)"
                >
                  修改
                </el-button>
                <el-button v-if="permissions.delete" type="primary" link size="small" @click="Delete(scope.row)">
                  删除
                </el-button>
                <el-button
                  v-if="permissions.auditing && scope.row.auditStatus == 0"
                  type="primary"
                  link
                  size="small"
                  @click="handleAudit(scope.row)"
                >
                  审核
                </el-button>
                <el-button v-if="permissions.detail" type="primary" link size="small" @click="Detail(scope.row)">
                  详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryForm.pageIndex"
            v-model:limit="queryForm.pageSize"
            @pagination="handleQuery"
          />
        </el-col>
      </el-row>
    </div>
    <add-form :dialog-add-or-edit="dialogAddOrEdit" @send-close="sendClose" />
    <detail :dialog-detail="dialogDetail" @send-close="sendClose" />
  </div>
</template>
<script setup lang="ts">
import addForm from "./addForm.vue";
import detail from "./detail.vue";
import { QueryProjectPage, DeleteProject, auditProject } from "@/api/project/projectInfo/index";
import { getDicts } from "@/store/modules/dict";

const permissions = ref({
  create: false,
  update: false,
  delete: false,
  detail: false,
  complet: false,
  bindManager: false,
  changeStatus: false,
  auditing: false,
  device: false,
});

const currentSystem = ref(localStorage.getItem("usertypeName"));
const isLumpContractor = ref(localStorage.getItem("isLumpContractor"));

if (currentSystem.value == "SysUser") {
  permissions.value = {
    create: true,
    update: true,
    delete: true,
    detail: true,
    complet: false,
    bindManager: false,
    changeStatus: false,
    auditing: true,
    device: true,
  };
}
if (currentSystem.value == "Corp") {
  if (isLumpContractor.value) {
    permissions.value = {
      create: true,
      update: true,
      delete: true,
      detail: true,
      complet: true,
      bindManager: true,
      changeStatus: true,
      auditing: false,
      device: true,
    };
  } else {
    permissions.value.detail = true;
  }
}
if (currentSystem.value == "Constructor") {
  permissions.value.detail = true;
}
if (currentSystem.value == "Manager") {
  permissions.value.create = true;
  permissions.value.update = true;
  permissions.value.delete = true;
  permissions.value.detail = true;
  permissions.value.complet = true;
}
if (currentSystem.value == "Commander") {
  permissions.value.detail = true;
  permissions.value.complet = true;
}

console.log(isLumpContractor);
console.log(currentSystem);
const loading = ref(false);
const tableData = ref();
const dialogAddOrEdit = reactive<DialogOption>({
  visible: false,
});
const dialogDetail = reactive<DialogOption>({
  visible: false,
});
const currentProject = ref();
const tableRef = ref();

//实现复选框的单选
const handleCurrentChange = function (selections: any, row: any) {
  if (selections.length > 1) {
    // 把数组的第一个元素从其中删除
    let del_row = selections.shift();
    // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
    tableRef.value.toggleRowSelection(del_row, false);
    currentProject.value = selections[0];
  } else {
    currentProject.value = selections[0];
  }
};

//新增
const Create = function () {
  dialogAddOrEdit.visible = true;
  dialogAddOrEdit.footBtn = "确认新增";
  dialogAddOrEdit.title = "新增";
};
//编辑
const Edit = function (row: any) {
  dialogAddOrEdit.visible = true;
  dialogAddOrEdit.id = row.projectId;
  dialogAddOrEdit.footBtn = "确认修改";
  dialogAddOrEdit.title = "修改";
};
const auditResult = ref("通过");
const handleAudit = async function (row: any) {
  auditResult.value = "通过";
  let box = await ElMessageBox({
    title: "项目审核",
    showCancelButton: true,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    message: () =>
      h(
        "div",
        {
          style: {
            display: "flex",
            "justify-content": "center",
            "align-items": "center",
          },
        },
        [
          h("span", null, "项目审核："),
          h(
            ElRadioGroup,
            {
              modelValue: auditResult.value,
              style: { width: "" },
              "onUpdate:modelValue": (val: any) => {
                auditResult.value = val;
              },
            },
            [
              h(ElRadioButton, {
                label: "通过",
              }),
              h(ElRadioButton, {
                label: "不通过",
              }),
            ]
          ),
        ]
      ),
  })
    .then((val) => true)
    .catch((val) => false);
  if (!box) {
    ElMessage({
      type: "info",
      message: "已取消审核！",
    });
    return;
  }
  loading.value = true;
  auditProject(Number(row.projectId), { auditStatus: auditResult.value === "通过" ? 1 : -1 })
    .then((data) => {
      if (data.success) {
        ElMessage({
          type: "success",
          message: "审核成功！",
        });
        handleQuery();
      } else {
        ElMessage({
          type: "error",
          message: data?.msg,
        });
      }
    })
    .catch((e) => {
      ElMessage({
        type: "error",
        message: e.toString(),
      });
    })
    .finally(() => {
      loading.value = false;
    });
};
//详情
const Detail = function (row: any) {
  dialogDetail.visible = true;
  dialogDetail.id = row.projectId;
  dialogDetail.title = "详情";
};

const sendClose = function (needRefresh: boolean) {
  dialogAddOrEdit.visible = false;
  dialogAddOrEdit.id = undefined;
  dialogDetail.visible = false;
  dialogDetail.id = undefined;
  if (needRefresh) {
    handleQuery();
  }
};

//删除
const Delete = function (row: any) {
  ElMessageBox.confirm("确定删除该项目吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      DeleteProject(row.projectId).then((res) => {
        if (res.type === 0) {
          if (res.success) {
            ElMessage({
              type: "success",
              message: res.msg,
            });
            handleQuery();
          } else {
            ElMessage({
              type: "error",
              message: res.msg,
            });
          }
        }
      });
    })
    .catch(() => {
      console.log("取消");
    });
};

//查询条件
const queryForm = reactive({
  keywords: "",
  pageIndex: 1,
  pageSize: 10,
});
const total = ref(0);

//这是列表数据
const handleQuery = function () {
  loading.value = true;
  QueryProjectPage(queryForm)
    .then((res) => {
      if (res.type === 0) {
        if (res.success) {
          tableData.value = res.data.list;
          queryForm.pageIndex = res.data.pageNum;
          queryForm.pageSize = res.data.pageSize;
          total.value = res.data.total;
        } else {
        }
      } else {
      }
    })
    .finally(() => {
      loading.value = false;
    });
};

onMounted(() => {
  handleQuery();
});
</script>
<style scoped>
:deep(.el-button) {
  margin-left: 5px;
}
:deep(.el-input__wrapper) {
  border-radius: 0;
}
</style>
